<?php
/*首页数据*/
namespace Admin\Model;
use Think\Model;
class OrderModel extends Model {
    const SHOW_NEW_COUNT=8;
    const INTOPRICE=1000;
    const INTOP=2000;
    public function getOrderData($data){
        $car       = M('order');//订单表
        $user      = M('user'); //用户表
        $wayuserid = M('wayuser');//渠道表
        $res       = $user->where(array('tel'=>$data['tel']))->find();
        return $res;
    }
    
    public function ListFieldData($json_true=false) {
        $order_mdb = M('order');
        $city_db   = D('city');
        $channel_db = D('Channel');
        $user_mdb = M('user');
        $admin_mdb = M('admin');
        $adminId = session('lampzuo_id');
        $admin_res = $admin_mdb -> where('id='.$adminId) -> field('position') -> find();

        if ($admin_res['position'] == 5) {
            $count= $order_mdb->where('status=0 and auditor = 0')->count();// 查询满足要求的总记录数
            $Page = new \Think\Page($count,15);// 实例化分页类 传入总记录数和每页显示的记录数(25)
            $order_data = $order_mdb->where(array('status'=>0, 'auditor_id' => $adminId,'auditor'=>0))->limit($Page->firstRow.','.$Page->listRows)->select();
        } else if ($admin_res['position'] == 501) {
            $count = $order_mdb ->where('status=0 AND auditor =1') -> count();
            $Page = new \Think\Page($count,15);// 实例化分页类 传入总记录数和每页显示的记录数(25)
            $order_data = $order_mdb->where(array('status'=>0,'auditor'=>1))->limit($Page->firstRow.','.$Page->listRows)->select();
        } else if ($admin_res['position'] == 502) {
            $count = $order_mdb -> join('jdc_cars on jdc_cars.carnum = jdc_order.carnum') -> where(array('status'=>0,'thirdparty_audit'=>0)) -> count();
            $Page = new \Think\Page($count,15);// 实例化分页类 传入总记录数和每页显示的记录数(25)
            $order_data = $order_mdb->where(array('status'=>0,'thirdparty_audit'=>0))->limit($Page->firstRow.','.$Page->listRows)->select();
        } else if ($admin_res['position'] == 503) {
            $count = $order_mdb -> join('jdc_cars on jdc_cars.carnum = jdc_order.carnum') -> where(array('status'=>0,'auditor'=>3,'thirdparty_audit'=>1)) -> count();
            $Page = new \Think\Page($count,15);// 实例化分页类 传入总记录数和每页显示的记录数(25)
            $order_data = $order_mdb->where(array('status'=>0,'auditor'=>3,'thirdparty_audit'=>1))->limit($Page->firstRow.','.$Page->listRows)->select();
        }
        if(!$order_data){
            return false;
        }
        $order_city = array_column($order_data,'cityid');
        $city_data = $city_db->CityGetAll(false,true);
        $order_data_json = [];
        for ($z=0; $z < count($order_data); $z++) { 
            $order_data[$z]['cityid'] = $city_data[$order_data[$z]['provinceid']]['shi'][$order_data[$z]['cityid']]['name'];
            $GW =  $this->OrderIndexAdmin($order_data[$z]['orderid'],'adminname');
            $action =  $this->OrderIndexAdmin($order_data[$z]['orderid'],'actionshijian','status=1')['create_time'];
            $udata =  $this->OrderIndexAdmin($order_data[$z]['uid'],'wayinfo');//
            $order_data[$z]['GWname'] = $GW['name'];
            $order_data[$z]['GWnum'] = $GW['usernum'];
            $order_data[$z]['waynum'] = $udata['waynum']?$udata['waynum']:'--';
            $order_data[$z]['waystatus'] = $channel_db->statuschannel($udata['status'])?$channel_db->statuschannel($udata['status']):'--';
            $order_data[$z]['customername'] = $user_mdb->where('id='.$order_data[$z]['uid'])->field('fullanme')->find()['fullanme'];
            $order_data[$z]['actiontime'] = date('Y-m-d H:i',$action);
            $order_data[$z]['create_time'] = date('Y-m-d H:i',$order_data[$z]['create_time']);
            if($json_true){
              $order_data_json[] = ['id'=>$order_data[$z]['id'],'d'=>$order_data[$z]];
            }
        }
        if($json_true){
          return ['data'=>$order_data_json,'page'=>$Page];
        }else{
          return ['data'=>$order_data,'page'=>$Page];
        }
    }

    /**
     * 全部订单(风控)
     */
    public function AllFkOrder() {
        $order_mdb = M('order');
        $order_operation_mdb = M('order_operation');
        $user_mdb = M('user');
        $admin_mdb = M('admin');
        $city_db   = D('city');
        $channel_db = D('Channel');
        $where_query = 'status<>0';
        $key = I('get.')['key'];
        if(!empty($key)){
          $admin_Gw_ids = $admin_mdb->where('name like "%'.$key.'%" or usernum like "%'.$key.'%"')->field('usernum')->select();
          if($admin_Gw_ids) {
            $admin_Gw_ids = '"'.implode('","', array_column($admin_Gw_ids, 'usernum')).'"';
            $admin_Gw_sql = ' and usernum in('.$admin_Gw_ids.')';
          } else {
            $admin_Gw_sql = '1=2';
          }
          $orderstatus = '0,1,-2,-1';
          $orderids = $order_operation_mdb
          ->where('status in ('.$orderstatus.')'.$admin_Gw_sql)
          ->select();
          if($orderids)
            $orderids = implode(',', array_column($orderids, 'orderid'));
          else
            $orderids = '0';
          $userids = $user_mdb->where('fullanme like "%'.$key.'%"')->field('id,fullanme')->select();
          if($userids) 
            $userids = implode(',',array_column($userids,'id'));
          else
            $userids = '0';
          $where_query .= ' and uid in('.$userids.') or orderid in('.$orderids.') and '.$where_query;
        }
        $count= $order_mdb->where($where_query)->count();// 查询满足要求的总记录数
        $Page = new \Think\Page($count,15);// 实例化分页类 传入总记录数和每页显示的记录数(25)
        $order_data = $order_mdb->where($where_query)->limit($Page->firstRow.','.$Page->listRows)->select();
        if(!$order_data){
            return false;
        }
        $order_city = array_column($order_data,'cityid');
        $city_data = $city_db->CityGetAll(false,true);
        $order_data_json = [];
        $order_status_arr = ['-2'=>'被驳回（正在修改）','-1'=>'被拒绝','0'=>'待审核（风控）','1'=>'待审核（城市经理）','2'=>'待签约','3'=>'已签约','4'=>"已确认收款",'5'=>'车辆已上牌','6'=>'已交付订单', '7' => '代审核(风控经理)'];
        for ($z=0; $z < count($order_data); $z++) {
            $ordercondition = '';
            $order_data[$z]['cityid'] = $city_data[$order_data[$z]['provinceid']]['shi'][$order_data[$z]['cityid']]['name'];
            $idorder = '1,-2,-1';
            $ordercondition .= 'status in ('.$idorder.')' ;
            $ordercondition .= ' and orderid ='.$order_data[$z]['orderid'];
            $ordercondition .= ' and usernum like "%F%"';
            $orderlist = $order_operation_mdb->where($ordercondition)->select();
            $order_data[$z]['adminname'] = [];
            $order_data[$z]['adminusernum']= [];
            foreach ($orderlist as $key => $value) {
              $adminum = $admin_mdb->where(array('usernum'=>$value['usernum']))->find();
              if(!in_array($adminum['usernum'],$order_data[$z]['adminusernum'])){
                  $order_data[$z]['adminusernum'][] = $adminum['usernum'];
              }
              if(!in_array($adminum['name'],$order_data[$z]['adminname'])){
                  $order_data[$z]['adminname'][] = $adminum['name'];
              }
            }
            $GW =  $this->OrderIndexAdmin($order_data[$z]['orderid'],'adminname');
            $action =  $this->OrderIndexAdmin($order_data[$z]['orderid'],'actionshijian','status=1')['create_time'];
            $udata =  $this->OrderIndexAdmin($order_data[$z]['uid'],'wayinfo');//
            $order_data[$z]['GWname'] = $GW['name'];
            $order_data[$z]['GWremark'] = $GW['remarks'];
            $order_data[$z]['GWnum'] = $GW['usernum'];
            $order_data[$z]['status'] = $order_status_arr[$order_data[$z]['status']];
            $order_data[$z]['waynum'] = $udata['waynum']?$udata['waynum']:'--';
            $order_data[$z]['waystatus'] = $channel_db->statuschannel($udata['status'])?$channel_db->statuschannel($udata['status']):'--';
            $order_data[$z]['customername'] = $user_mdb->where('id='.$order_data[$z]['uid'])->field('fullanme')->find()['fullanme'];
            $order_data[$z]['actiontime'] = date('Y-m-d H:i',$action);
            $order_data[$z]['create_time'] = date('Y-m-d H:i',$order_data[$z]['create_time']);
            
        }
        return ['data'=>$order_data,'page'=>$Page];
    }

    /** 
     * 订单详情信息
     */
    public function OrderInfo($orderid) {
        $order_mdb  = M('order');
        $carprice   = M('car_price');
        $price_db = M('price');
        $city_db    = D('city');
        $jdcstock_db= D('stock');
        $cars_db    = D('Cars');
        $cars_stock = M('cars_stock');
        $customer_db= D('customer');
        $order_data = $order_mdb->where('id='.$orderid)->find();
        $sokeid = $cars_stock->where(array('id'=>$order_data['stockid']))->find();
        $stockku   = $jdcstock_db->where(array('id'=>$sokeid['sid']))->find();
        $soke_city_id = $city_db->where(array('id'=>$sokeid['cityid']))->find()['name'];
        $GW =  $this->OrderIndexAdmin($order_data['orderid'],'adminname');
        $citydata = $city_db->GetCityInfo($order_data['cityid'],'city_orderinfo');
        $udata =   $this->OrderIndexAdmin($order_data['uid'],'wayinfo');
        $car_Data = $cars_db->OneCarData(['carnum'=>$order_data['carnum']],['name','type','details']);
        $carpricedata =$carprice->where(array('carnum'=>$order_data['carnum'],'version'=>$order_data['price_version']))->field('first_pay,month_pay,jdc_price')->find();
        if($order_data['create_time'] > 1527838056){
           $carpricedata =$price_db->where(array('id'=>$order_data['price_version_id'],'version'=>$order_data['price_version']))->field('first_pay,month_pay,surplus_money,pay_month,purchase_tax,insurance')->find();
        }
        $provinceidata = $city_db->GetCityInfo($citydata['pid'],'city_name');

        $order_data['GWname'] = $GW['name'];
        $order_data['GWnum'] = $GW['usernum'];
        $order_data['GWremark'] = $GW['remarks'];
        $order_data['cityid'] = $citydata['name'];
        $order_data['provinceid'] = $provinceidata['name'];
        $order_data['waynum'] = $udata['waynum'];
        $order_data['carname'] = $car_Data['name'].$car_Data['details'];
        $order_data['cartype'] = $car_Data['type'];
        $order_data['carservice']   = $carpricedata['first_pay'];
        $order_data['carmonthpay']   = $carpricedata['month_pay'];
        $order_data['surplus_money'] = $carpricedata['surplus_money'];
        $order_data['purchase_tax']  = $carpricedata['purchase_tax'];
        $order_data['pay_month']     = $carpricedata['pay_month'];
        $order_data['insurance']     = $carpricedata['insurance'];
        $order_data['soket'] = $stockku['city'];
        $order_mdb->where('id='.$orderid)->save(array('last_update'=>$order_data['create_time']));
        return $order_data;
    }

    /**
     * 已付款订单
     */
    public function OrderAlreadyPay() {
        $price_db       = M('price');//价格表
        $order_mdb = M('order');
        $orderPay_mdb  = M('order_pay');
        $orderOper_mdb = M('order_operation');
        $car_mdb = M('cars');
        $carprice = M('car_price');
        $car_stock_mdb = M('cars_stock');
        $user_mdb = M('user');
        $city_mdb = M('city');
        $count= $order_mdb->where('status>=2 and status<=3')->count();// 查询满足要求的总记录数
        $Page = new \Think\Page($count,15);// 实例化分页类 传入总记录数和每页显示的记录数(25)
        $order_data = $order_mdb->where('status>=2 and status<=3')->limit($Page->firstRow.','.$Page->listRows)->select();
        $order_status_arr = ['-2'=>'被驳回（正在修改）','-1'=>'被拒绝','0'=>'待审核（风控）','1'=>'待审核（城市经理）','2'=>'待签约','3'=>'已签约','4'=>"已确认收款",'5'=>'车辆已上牌','6'=>'已完结订单'];
        foreach ($order_data as $k => $v) {
            if($v['status']=='3'){
              $actioninfo = $orderOper_mdb->join('jdc_admin as a on jdc_order_operation.usernum=a.usernum')->where('jdc_order_operation.orderid='.$v['orderid'].' and jdc_order_operation.status=3')->field('a.name,jdc_order_operation.create_time')->find();
            }
            $payinfo = $user_mdb->where(array('id'=>$v['uid']))->find();
            $city_add= $city_mdb->where(array('id'=>$v['cityid']))->find()['name'];
            $prov_add= $city_mdb->where(array('id'=>$v['provinceid']))->find()['name'];
            $carinfo = $car_mdb->where('carnum='.$v['carnum'])->field('type,name,brand,details')->find();
            if($v['create_time'] >  1527838056){
               $priceversion    = $price_db->where(array('id'=>$v['price_version_id']))->field('month_pay,first_pay,pay_month,insurance,surplus_money')->find();
               $priceinfo['month_pay'] = $priceversion['month_pay'];
               $priceinfo['first_pay'] = $priceversion['first_pay'];
            }else{
              $priceinfo = $carprice->where(array('carnum'=>$v['carnum'],'version'=>$v['price_version']))->field('guide_price,first_pay,jdc_price,month_pay')->find();
            }
            $stock = $car_stock_mdb->where(array('id'=>$v['stockid']))->field('color')->find();
            $GW =  $this->OrderIndexAdmin($v['orderid'],'adminname');
            if($v['status']=='3'){
              $v['actionname'] = $actioninfo['name'];
              $v['pay_time'] = date('Y-m-d H:i:s',$actioninfo['create_time']);
            }else{
              $v['actionname'] = '未签约';
              $v['pay_time'] = '未签约';
              $v['contract'] = '未签约';
            }
            $v['first_pay'] = $priceinfo['first_pay'];
            $v['firstpaymonthpay'] = $priceinfo['first_pay']+$priceinfo['month_pay']+$priceinfo['zz_month_pay'];
            $v['cartype'] = $carinfo['type'];
            $v['carname'] = $carinfo['name'].' '.$carinfo['details'];
            $v['month_pay'] = $priceinfo['month_pay'];
            $v['carbrand'] = $carinfo['brand'];
            $v['carcolor'] = $stock['color'];
            $v['customername'] = $payinfo['nickname'];
            $v['bank'] = $payinfo['bank'];
            $v['banker'] = $payinfo['banker'];
            $v['banknum'] = $payinfo['banknum'];
            $v['cityname'] = $city_add;
            $v['provinceid'] = $prov_add;
            $v['guide_price'] = $priceinfo['guide_price'];
            $v['GWname'] = $GW['name'];
            $v['GWnum'] = $GW['usernum'];
            $v['statustext'] = $order_status_arr[$v['status']];
            $order_data[$k] = $v;
        }
        return ['data'=>$order_data,'page'=>$Page];
    }

    /**
     * 历史操作
     * 名称叫历史订单:订单号，车辆编号，客户姓名，银行名称，银行账户名，银行卡号，服务费，
     * 月租金，已还期数，下次还款金额，下次还款时间,车辆名称
     */ 
    public function OrderHistoryFinance() {
      $order_mdb = M('order');
      $admin_mdb = M('admin');
      $orderPay_mdb  = M('order_month_pay');
      // $orderPay_mdb  = M('order_pay');
      $orderOper_mdb = M('order_operation');
      $car_mdb  = M('cars');
      $user_mdb = M('user');
      $city_mdb = M('city');
      $price_db = M('price');
      $carprice = M('car_price');
      $meid = session('lampzuo_id');
      $count= $order_mdb->where('status=3')->count();// 查询满足要求的总记录数
      $Page = new \Think\Page($count,15);// 实例化分页类 传入总记录数和每页显示的记录数(25)
      $admindata = $admin_mdb->where('id='.$meid)->find();
      $historyOrder = $orderOper_mdb->where('jdc_order_operation.status=4')
      ->field('jdc_order.orderid,jdc_order_operation.usernum,jdc_order.carnum,jdc_order.uid,jdc_order.price_version,jdc_order.price_version_id,jdc_order.create_time')
      ->join('left join jdc_order on jdc_order.orderid=jdc_order_operation.orderid')
      ->limit($Page->firstRow.','.$Page->listRows)
      ->select();
      for ($i=0; $i < count($historyOrder); $i++) { 
        $cardata = $car_mdb->where('carnum='.$historyOrder[$i]['carnum'])->field('name,carnum')->find();
        if($historyOrder[$i]['create_time'] >  1527838056){
           $priceversion    = $price_db->where(array('id'=>$historyOrder[$i]['price_version_id']))->field('month_pay,first_pay,pay_month,insurance,surplus_money')->find();
           $cardata['month_pay'] = $priceversion['month_pay'];
           $cardata['first_pay'] = $priceversion['first_pay'];
        }else{
          $priceinfo = $carprice->where(array('carnum'=>$historyOrder[$i]['carnum'],'version'=>$historyOrder[$i]['price_version']))->field('guide_price,first_pay,jdc_price,month_pay')->find();
          $cardata['month_pay'] = $priceinfo['month_pay'];
          $cardata['first_pay'] = $priceinfo['first_pay'];
        }
        
        $userdata = $user_mdb->where('id='.$historyOrder[$i]['uid'])->field('bank,banker,banknum,id,fullanme')->find();
        $orderPaydata = $orderPay_mdb->where('status <> 1 and orderid='.$historyOrder[$i]['orderid'])->find();
        $orderPayMonth= $orderPay_mdb->where('status = 1 and orderid='.$historyOrder[$i]['orderid'])->find();
        $datatime= date("Y-m-d",$orderPaydata['pay_time']);
        $orderPaydata['pay_month'] = $orderPayMonth['pay_month'];
        $orderPaydata['pay_time'] = $datatime;
        $historyOrder[$i]['cardata'] = $cardata;
        $historyOrder[$i]['userdata'] = $userdata;
        $historyOrder[$i]['orderPaydata'] = $orderPaydata;
      }
      return ['data'=>$historyOrder,'page'=>$Page];
    }
   
    /**
     * 添加订单
     */
    public function getAddOrder($data,$addlist){

        $car        = M('order');// 订单表
        $operation  = M('order_operation');// 操作表
        $admin      = M('admin'); // 员工表
        $user       = M('user'); // 用户表
        $carprice   = M('car_price'); // 记录表
        $carprr     = $carprice->where(array('is_new'=>1,'carnum'=>$data['provs']))->field('version')->find();
        if($data['orderid']){
            if($data['orderstatus'] == 2){
                    $ationdata = array(
                      "last_update" => time(),
                      "remark" => "修改订单",
                      "uid"    => $data['uid'],
                      "status" => -1,
                      "carnum" => $data['provs'],
                      "orderstatus" => $data['orderstatus'],
                      "stockid" => $data['cities'],
                      "projecttype"     => $data['projecttype'],
                    );
            }else{
                    $ationdata = array(
                      "last_update" => time(),
                      "remark" => "修改订单",
                      "uid"    => $data['uid'],
                      "status" => 0,
                      "carnum" => $data['provs'],
                      "stockid"=> $data['cities'],
                      "price_version"   => $data['version'],
                      "price_version_id"=> $data['version_id'],
                      "orderstatus"     => $data['orderstatus'],
                      "projecttype"     => $data['projecttype'],
                    );
            }
            $caryh = $car->where(array('orderid'=>$data['orderid']))->find();
            if($caryh){
               $ret = $car->where(array('orderid'=>$data['orderid']))->save($ationdata);
               $addlist['nickname']  = $data['banker'];
               $addlist['income']    = $data['income'];
               $addlist['bank']      = $data['bank'];
               $addlist['banker']    = $data['banker'];
               $addlist['banknum']   = $data['banknum'];
               $addlist['marriage']  = $data['marriage'];
               $addlist['workunit']  = $data['workunit'];
               $addlist['creditcard']= $data['creditcard'];
               $addlist['borrowing'] = $data['borrowing'];
               $addlist['identify']  = $data['identify'];
               $addlist['minority']  = $data['minority'];
               $addlist['fullanme']  = $data['fullanme'];
               $addlist['birthday']  = $data['birthday'];
               $addlist['sex']       = $data['sex'];
               $addlist['address']   = $data['address'];
               $addlist['usertype']   = $data['usertype'];
               $addlist['liveaddress']   = $data['liveaddress'];
               $addlist['companyaddress']   = $data['companyaddress'];
               $addlist['housingnature']   = $data['housingnature'];
               $addlist['contacts_phone']       = $data['contactsphone1'];
               $addlist['contacts_name']        = $data['contactsname1'];
               $addlist['contacts_bearing']     = $data['contactsbearing1'];
               $addlist['contacts_phone_tel']   = $data['contactsphone2'];
               $addlist['contacts_user_name']   = $data['contactsname2'];
               $addlist['contacts_sip_bearing'] = $data['contactsbearing2'];
               $res = $user->where(array('tel'=>$data['tel']))->save($addlist);
               if($ret || $res){
                    return true;
               }else{
                    return false;
               }
            }
        }else{
                $orid       = date("Ymd",time());
                $time1      = $car->order('id desc')->find();
                $datetime   = substr($time1['orderid'],0,8);
                $time       = substr($time1['orderid'],8);
                if($datetime == $orid){
                   $addtime = $time1['orderid'] += 1;
                }else{
                   $time = 1000;
                   $addtime = $orid.$time +=1;
                }
                $map['id']  = array('EQ',session('lampzuo_id'));
                $res = $admin->where($map)->find();
                if(!$res){
                    return array("ret"=>1,"msg"=>"请登录"); 
                }
                if($data['orderstatus'] == 2){
                    //内拒订单
                    $ationdata = array(
                        "create_time" => time(),
                        "last_update" => time(),
                        "remark" => "创建订单内拒",
                        "uid"    => $data['uid'],
                        "status" => -1,
                        "orderid"=> $addtime,
                        "carnum" => $data['provs'],
                        "cityid" => $res['cityid'],
                        "orderstatus"     => $data['orderstatus'],
                        "stockid"         => $data['cities'],
                        "provinceid"      => $res['provinceid'],
                        "price_version"   => $data['version'],
                        "price_version_id"=> $data['version_id'],
                        "address"         => $data['gpsaddress'],
                        "projecttype"     => $data['projecttype'],

                        );
                }else{
                    //创建订单
                    $ationdata = array(
                        "create_time" => time(),
                        "last_update" => time(),
                        "remark" => "创建订单",
                        "uid"    => $data['uid'],
                        "status" => 0,
                        "orderid"=> $addtime,
                        "carnum" => $data['provs'],
                        "cityid" => $res['cityid'],
                        "orderstatus"     => $data['orderstatus'],
                        "stockid"         => $data['cities'],
                        "provinceid"      => $res['provinceid'],
                        "price_version"   => $data['version'],
                        "price_version_id"=> $data['version_id'],
                        "address"         => $data['gpsaddress'],
                        "projecttype"     => $data['projecttype'],
                        );
                    $auditors = $admin -> where(array('position' => 5,'test_sign'=>0)) -> select();
                    $auditorCount = count($auditors);
                    $orderCount = $car -> where(array('orderstatus' => 1)) -> count();
                    $auditor = $auditors[$orderCount % $auditorCount];
                    $ationdata['auditor_id'] = $auditor['id'];
                }
                //记录操作人
                $adduserdata = array(
                        "orderid" => $addtime,
                        "usernum" => $res['usernum'],
                        "status"  => 0,
                        "remark"  => "创建订单",
                        "create_time"=> time(),
                );

                if($car->add($ationdata) && $operation->add($adduserdata)){
                   //修改用户信息
                   $addlist['nickname'] = $data['banker'];
                   $addlist['income']   = $data['income'];
                   $addlist['bank']     = $data['bank'];
                   $addlist['banker']   = $data['banker'];
                   $addlist['banknum']  = $data['banknum'];
                   $addlist['marriage'] = $data['marriage'];
                   $addlist['workunit'] = $data['workunit'];
                   $addlist['creditcard']    = $data['creditcard'];
                   $addlist['borrowing']     = $data['borrowing'];
                   $addlist['policeoffice']  = $data['policeoffice'];
                   $addlist['identify']  = $data['identify'];
                   $addlist['minority']  = $data['minority'];
                   $addlist['fullanme']  = $data['fullanme'];
                   $addlist['birthday']  = $data['birthday'];
                   $addlist['sex']       = $data['sex'];
                   $addlist['address']   = $data['address'];
                   $addlist['usertype']  = $data['usertype'];
                   $addlist['liveaddress']   = $data['liveaddress'];
                   $addlist['companyaddress']   = $data['companyaddress'];
                   $addlist['housingnature']   = $data['housingnature'];
                   $addlist['contacts_phone']       = $data['contactsphone1'];
                   $addlist['contacts_name']        = $data['contactsname1'];
                   $addlist['contacts_bearing']     = $data['contactsbearing1'];
                   $addlist['contacts_phone_tel']   = $data['contactsphone2'];
                   $addlist['contacts_user_name']   = $data['contactsname2'];
                   $addlist['contacts_sip_bearing'] = $data['contactsbearing2'];
                   $result = $user-> where(array('tel'=>$data['tel']))->save($addlist);
                   return $result;
                }else{
                    return null;
                } 
        }        
    }
    /**
     * 获取要的修改订单并返回数据
     */
    public function getSaveOrder($data){
        $order     = M('Order');
        $user      = M('User');
        $Cars      = M('Cars');
        $res       = $order->where(array('orderid'=>$data['orderid']))->find();
        $carslit   = $Cars->where(array('carnum'=>$res['carnum']))->find();
        if ($res) {
           $addres = $user->where(array('id'=>$res['uid']))->find();
           $addres['identify_url']  = serializeMysql($addres['identify_url'],1);
           $addres['driver_url']    = serializeMysql($addres['driver_url'],1);
           $addres['workproof_url'] = serializeMysql($addres['workproof_url'],1);
           $addres['bankflow_url']  = serializeMysql($addres['bankflow_url'],1);
           $addres['creditreport_url']= serializeMysql($addres['creditreport_url'],1);
           $addres['otherdata_url']= serializeMysql($addres['otherdata_url'],1);
           $addres['orderid']    = $res['orderid'];
           $addres['uid']        = $res['uid'];
           $addres['carnum']     = $res['carnum'];
           $addres['provinceid'] = $res['provinceid'];
           $addres['cityid']     = $res['cityid'];
           $addres['orderstatus']= $res['orderstatus'];
           $addres['stockid']    = $res['stockid'];
           $addres["version"]    = $res['price_version'];
           $addres["version_id"] = $res['price_version_id'];
           $addres['name']       = $carslit['name'];
           $addres['guide_price']= $carslit['guide_price'];
           $addres['jdc_price']  = $carslit['jdc_price'];
        }else{
            return false;
        }
        return $addres;
    }
    /**
     * 返回订单列表|| intval($data) == 4 || intval($data) == 3
     * @return [type] [description]
     */
    public function getListOrder($data,$result = ""){
      $limit = 10;
      $page = intval($result['page']);
      if($page>0) {
        // $jlr = I('get.page');
        $limit2 = intval($page);
        $index = [intval($page)*$limit,$limit];
      }else{
        $index = [0,$limit];
      }
      $jt=strtotime(date("Y-m-d",strtotime("-1 day")).' 23:59:59');
      $order = M('order');
      $orderoperation = M('order_operation');
      $user = M('user');
      $cars = M('cars');
      // $orderpay = M('order_pay');
      $orderpay = M('order_month_pay');
      if (intval($data['position']) == 1) {
          $am = "1=1";
          $am.= " and status = 0";
          $am.= " and usernum = '".$data['usernum']."'";
          $res =  $orderoperation->where($am)->field('orderid')->select();
          //===============操作数据=================
          $sum  = $this->getForInSta($res);
          $where ="1=1";
          //状态(-2代表暂拒可重新申请订单，-1被拒订单，0才创建的订单，1风控已审核通过订单，2城市经理人审核通过订单，3用户已签约，4确认收款,5代表车辆已上牌，6代表交易完成订单,)
          if($result['statusid'] == "1"){
              $where .=" and status <> 6";//未完成
          }elseif ($result['statusid'] == "2") {
              $where .=" and status in ('0','1','7')";
          }elseif ($result['statusid'] == "3") {
              $where .= " and status >= 2";//未签约订单
              $where .= " and status < 4";
          }elseif ($result['statusid'] == "4") {
              // $where .= " and status = 5";//车辆上牌和等待上牌
              $where .= " and status = 4";
              // $where .= " and status < 6";
          }elseif ($result['statusid'] == "5") {
              $where .= " and status = 6";//完成交易
          }elseif ($result['statusid'] == "6") {
              $where .= " and status = 5";//等待提车
          }elseif($result['statusid'] == "7"){
              $tiems = time();
              $d  = "1=1";
              $d .=" and orderid in (".$sum.")";
              $d .=" and pay_time <= ".$tiems;
              $d .=" and status <> 1";
              $payarr = $orderpay->where($d)->select();
              $sum1 = $this->getForInSta($payarr);
              $where .=" and orderid in (".$sum1.")";
              $where .=" and status = 6";
          }
          if($result['statusid'] != "7"){
              $where .=" and orderid in (".$sum.")";
          }
          $search = $result['searchid'];
          if(preg_match("/^([\x{4e00}-\x{9fa5}]+)$/u", $search) || preg_match("/^[a-z]+$/i", $search)){
              $whe  ="1=1";
              $whe .= " and nickname like '%{$search}%'";
              $usercondition = $user->where($whe)->select();
              $count = count($usercondition);
              for($i = 0; $i < $count; $i++){
                  if($s){
                      $s.=",'".$usercondition[$i]['id']."'";
                  }else{
                      $s.="'".$usercondition[$i]['id']."'";
                  }
              }
              $where .=" and uid in (".$s.")";

          }else if($search){
              $where .= " and orderid like '%{$search}%'";
          }
          //过滤订单被拒第二天不显示
          $ww = "1=1";
          $ww .= " and status = -1";
          $ww .= " and create_time < ".$jt;
          $arra = $order->where($ww)->select();
          $zfc  = $this->getForInSta($arra);
          if($zfc){
            $where .=" and orderid not in (".$zfc.")";  
          }
          $resadd = $order->where($where)->order('status asc') ->limit($index[0],$index[1])->select();
          //==============订单用户和车辆数据==================
          $count1 = count($resadd);
          for($i = 0; $i < $count1; $i++){
              if($sum1){
                  $sum1.=",'".$resadd[$i]['uid']."'";
              }else{
                  $sum1.="'".$resadd[$i]['uid']."'";
              }
              if($sum2){
                  $sum2.=",'".$resadd[$i]['carnum']."'";
              }else{
                  $sum2.="'".$resadd[$i]['carnum']."'";
              }
          }
          $m   ="1=1";
          $m  .=" and id in (".$sum1.")";
          $ma  ="1=1";
          $ma .=" and carnum in (".$sum2.")";
          $useradd = $user->where($m)->field('id,nickname,tel,waynum')->select();
          $carsadd = $cars->where($ma)->field('name,carnum,type')->select();
          $arr = array();
          foreach ($resadd as $key => $value) {
              foreach ($useradd as $ke => $va) {
                  if($value['uid'] == $va['id']){
                      $resadd[$key]['nickname'] = $va['nickname'];
                  }
              }
              foreach ($carsadd as $k => $v) {
                  if($v['carnum'] == $value['carnum']){
                      $resadd[$key]['name'] = $v['name'];
                      $resadd[$key]['first_pay'] = $v['first_pay'];
                      $resadd[$key]['guide_price'] = $v['guide_price'];
                      $resadd[$key]['type'] = $v['type'];
                  }
              }
             
          }
          return $resadd;
      }elseif (intval($data['position']) == 2) {
          $m  ="1=1";
          $m .=" and provinceid = ".$data['provinceid'];
          $m .=" and status >= 2";
          $search = $result['searchid'];
          if(preg_match("/^([\x{4e00}-\x{9fa5}]+)$/u", $search) || preg_match("/^[a-z]+$/i", $search)){
              $whe  ="1=1";
              $whe .= " and nickname like '%{$search}%'";
              $usercondition = $user->where($whe)->select();
              $count = count($usercondition);
              for($i = 0; $i < $count; $i++){
                  if($s){
                      $s.=",'".$usercondition[$i]['id']."'";
                  }else{
                      $s.="'".$usercondition[$i]['id']."'";
                  }
              }
              $m .=" and uid in (".$s.")";

          }else if($search){
              $m .= " and orderid like '%{$search}%'";
          }
          //过滤完成单第二天不显示
          $ww   = "1=1";
          $ww  .= " and status = 6";
          $ww  .= " and create_time < ".$jt;
          $arra = $order->where($ww)->select();
          $zfc  = $this->getForInSta($arra);
          if($zfc){
            $m .=" and orderid not in (".$zfc.")";  
          }
          $res  =  $order->where($m)->order('status asc')->limit($index[0],$index[1])->select();
          $count1 = count($res);
          for($i = 0; $i < $count1; $i++){
              if($sum1){
                  $sum1.=",'".$res[$i]['uid']."'";
              }else{
                  $sum1.="'".$res[$i]['uid']."'";
              }
              if($sum2){
                  $sum2.=",'".$res[$i]['carnum']."'";
              }else{
                  $sum2.="'".$res[$i]['carnum']."'";
              }
          }
          $m  ="1=1";
          $m .=" and id in (".$sum1.")";
          $ma  ="1=1";
          $ma .=" and carnum in (".$sum2.")";
          $useradd = $user->where($m)->field('id,nickname,tel,waynum')->select();
          $carsadd = $cars->where($ma)->field('name,carnum,type')->select();
          foreach ($res as $key => $value) {
              foreach ($useradd as $ke => $va) {
                  if($value['uid'] == $va['id']){
                      $res[$key]['nickname'] = $va['nickname'];
                  }
              }
              foreach ($carsadd as $k => $v) {
                  if($v['carnum'] == $value['carnum']){
                      $res[$key]['name'] = $v['name'];
                      $res[$key]['first_pay'] = $v['first_pay'];
                      $res[$key]['guide_price'] = $v['guide_price'];
                      $res[$key]['type'] = $v['type'];
                  }
              }
          }
          return $res;
      }elseif (intval($data['position']) == 3) {
          $where  ="1=1";
          // $where .= " and cityid =".$data['cityid'];
          $admin  = M("admin");
          $orderoperation = M("order_operation");
          $ww    = "1=1";
          $ww   .= " and pid = ".$data['id'];
          $resdata =  $admin->where($ww)->select();            
          $count1 = count($resdata);
          for($i = 0; $i < $count1; $i++){
              if($sum2){
                  $sum2.=",'".$resdata[$i]['usernum']."'";
              }else{
                  $sum2.="'".$resdata[$i]['usernum']."'";
              }
          }
          $wdecityid   = "1=1"; 
          $wdecityid  .= " and status = 0"; 
          $wdecityid  .= " and usernum in (".$sum2.")"; 
          $citydata    =  $orderoperation->where($wdecityid)->field('orderid')->select();
          $arrorder    = $this->getForInSta($citydata);
          $where    .= " and orderid in (".$arrorder.")"; 
          $search = $result['searchid'];
          if(preg_match("/^([\x{4e00}-\x{9fa5}]+)$/u", $search) || preg_match("/^[a-z]+$/i", $search)){
              $whe  ="1=1";
              $whe .= " and nickname like '%{$search}%'";
              $usercondition = $user->where($whe)->select();
              $count = count($usercondition);
              for($i = 0; $i < $count; $i++){
                  if($s){
                      $s.=",'".$usercondition[$i]['id']."'";
                  }else{
                      $s.="'".$usercondition[$i]['id']."'";
                  }
              }
              $where .=" and uid in (".$s.")";

          }else if($search){
              $where .= " and orderid like '%{$search}%'";
          }
          if($result['statusid'] == "1"){
              $where .=" and status <> 6";//未完成
              $where .=" and status <> -1";
          }elseif ($result['statusid'] == "2") {
              $where .=" and status in ('0','1','7')";
          }elseif ($result['statusid'] == "3") {
              // $where .= " and status = 2";//未签约订单
              $where .= " and status >= 2";
              $where .= " and status < 4";
          }elseif ($result['statusid'] == "4") {
              // $where .= " and status = 5";//车辆上牌和等待上牌
              $where .= " and status = 4";
          }elseif ($result['statusid'] == "5") {
              $where .= " and status = 6";//完成交易
          }elseif ($result['statusid'] == "6") {
              $where .= " and status = 5";//等待提车
          }elseif($result['statusid'] == "7"){
              $tiems = time();
              $d  = "1=1";
              $d .=" and pay_time <= ".$tiems;
              $d .=" and status <> 1";
              $payarr = $orderpay->where($d)->select();
              $sum1   = $this->getForInSta($payarr);
              $where .=" and orderid in (".$sum1.")";
              $where .=" and orderid in (".$arrorder.")";
              $where .= " and status = 6";
          }
          $ww = "1=1";
          $ww .= " and status = -1";
          $ww .= " and create_time < ".$jt;
          $ww .= " and orderid in (".$arrorder.")";
          $arra = $order->where($ww)->select();
          $zfc  = $this->getForInSta($arra);
          if($zfc){
            $where .=" and orderid not in (".$zfc.")";  
          }
          $res =  $order->where($where)->limit($index[0],$index[1])->select();
          
          $count1 = count($res);
          for($i = 0; $i < $count1; $i++){
              if($sum1){
                  $sum1.=",'".$res[$i]['uid']."'";
              }else{
                  $sum1.="'".$res[$i]['uid']."'";
              }
              if($sum2){
                  $sum2.=",'".$res[$i]['carnum']."'";
              }else{
                  $sum2.="'".$res[$i]['carnum']."'";
              }
          }
          $m  ="1=1";
          $m .=" and id in (".$sum1.")";
          $ma  ="1=1";
          $ma .=" and carnum in (".$sum2.")";
          $useradd = $user->where($m)->field('id,nickname,tel,waynum')->select();
          $carsadd = $cars->where($ma)->field('name,carnum,type')->select();
          foreach ($res as $key => $value) {
              foreach ($useradd as $ke => $va) {
                  if($value['uid'] == $va['id']){
                      $res[$key]['nickname'] = $va['nickname'];
                  }
              }
              foreach ($carsadd as $k => $v) {
                  if($v['carnum'] == $value['carnum']){
                      $res[$key]['name'] = $v['name'];
                      $res[$key]['first_pay'] = $v['first_pay'];
                      $res[$key]['guide_price'] = $v['guide_price'];
                      $res[$key]['type'] = $v['type'];
                  }
              }
          }
          return $res;
      }elseif (intval($data['position']) == 4) {
          $where  ="1=1";
          $where .= " and provinceid =".$data['provinceid'];
          $search = $result['searchid'];
          if(preg_match("/^([\x{4e00}-\x{9fa5}]+)$/u", $search) || preg_match("/^[a-z]+$/i", $search)){
              $whe  ="1=1";
              $whe .= " and nickname like '%{$search}%'";
              $usercondition = $user->where($whe)->select();
              $count = count($usercondition);
              for($i = 0; $i < $count; $i++){
                  if($s){
                      $s.=",'".$usercondition[$i]['id']."'";
                  }else{
                      $s.="'".$usercondition[$i]['id']."'";
                  }
              }
              $where .=" and uid in (".$s.")";
          }else if($search){
              $where .= " and orderid like '%{$search}%'";
          }
          if($result['statusid'] == "1"){
              $where .=" and status <> 6";//未完成
              $where .=" and status <> -1";
          }elseif ($result['statusid'] == "2") {
              $where .=" and status in ('0','1','7')";
          }elseif ($result['statusid'] == "3") {
              // $where .= " and status = 2";//未签约订单
              $where .= " and status >= 2";
              $where .= " and status < 4";
          }elseif ($result['statusid'] == "4") {
              // $where .= " and status = 5";//车辆上牌和等待上牌
              $where .= " and status = 4";
              // $where .= " and status < 5";
          }elseif ($result['statusid'] == "5") {
              $where .= " and status = 6";//完成交易
          }elseif ($result['statusid'] == "6") {
              $where .= " and status = 5";//等待提车
          }elseif($result['statusid'] == "7"){
              $tiems = time();
              $d  = "1=1";
              $d .=" and pay_time <= ".$tiems;
              $d .=" and status <> 1";
              $payarr = $orderpay->where($d)->select();
              $sum1  = $this->getForInSta($payarr);
              
              $where .=" and orderid in (".$sum1.")";
              $where .= " and status = 6";
          }
          $ww   = "1=1";
          $ww  .= " and status = -1";
          $ww  .= " and create_time < ".$jt;
          $arra = $order->where($ww)->select();
          $zfc  = $this->getForInSta($arra);
          if($zfc){
            $where .=" and orderid not in (".$zfc.")";  
          }
          $res =  $order->where($where)->limit($index[0],$index[1])->select();
          $count1 = count($res);
          for($i = 0; $i < $count1; $i++){
              if($sum1){
                  $sum1.=",'".$res[$i]['uid']."'";
              }else{
                  $sum1.="'".$res[$i]['uid']."'";
              }
              if($sum2){
                  $sum2.=",'".$res[$i]['carnum']."'";
              }else{
                  $sum2.="'".$res[$i]['carnum']."'";
              }
          }
          $m  ="1=1";
          $m .=" and id in (".$sum1.")";
          $ma  ="1=1";
          $ma .=" and carnum in (".$sum2.")";
          $useradd = $user->where($m)->field('id,nickname,tel,waynum')->select();
          $carsadd = $cars->where($ma)->field('name,carnum,type')->select();
          foreach ($res as $key => $value) {
              foreach ($useradd as $ke => $va) {
                  if($value['uid'] == $va['id']){
                      $res[$key]['nickname'] = $va['nickname'];
                  }
              }
              foreach ($carsadd as $k => $v) {
                  if($v['carnum'] == $value['carnum']){
                      $res[$key]['name'] = $v['name'];
                      $res[$key]['first_pay'] = $v['first_pay'];
                      $res[$key]['guide_price'] = $v['guide_price'];
                      $res[$key]['type'] = $v['type'];
                  }
              }
          }
          return $res;
      }elseif(intval($data['position']) == 1100){

          $where  ="1=1";
          // $where .= " and provinceid =".$data['provinceid'];
          $search = $result['searchid'];
          if(preg_match("/^([\x{4e00}-\x{9fa5}]+)$/u", $search) || preg_match("/^[a-z]+$/i", $search)){
              $whe  ="1=1";
              $whe .= " and nickname like '%{$search}%'";
              $usercondition = $user->where($whe)->select();
              $count = count($usercondition);
              for($i = 0; $i < $count; $i++){
                  if($s){
                      $s.=",'".$usercondition[$i]['id']."'";
                  }else{
                      $s.="'".$usercondition[$i]['id']."'";
                  }
              }
              $where .=" and uid in (".$s.")";
          }else if($search){
              $where .= " and orderid like '%{$search}%'";
          }
          if($result['statusid'] == "1"){
              $where .=" and status <> 6";//未完成
              // $where .=" and status <> -1";
          }elseif ($result['statusid'] == "2") {
              $where .=" and status in ('0','1','7')";
          }elseif ($result['statusid'] == "3") {
              // $where .= " and status = 2";//未签约订单
              $where .= " and status >= 2";
              $where .= " and status < 4";
          }elseif ($result['statusid'] == "4") {
              // $where .= " and status = 5";//车辆上牌和等待上牌
              $where .= " and status = 4";
              // $where .= " and status < 5";
          }elseif ($result['statusid'] == "5") {
              $where .= " and status = 6";//完成交易
          }elseif ($result['statusid'] == "6") {
              $where .= " and status = 5";//等待提车
          }elseif($result['statusid'] == "7"){
              $tiems = time();
              $d  = "1=1";
              $d .=" and pay_time <= ".$tiems;
              $d .=" and status <> 1";
              $payarr = $orderpay->where($d)->select();
              $sum1  = $this->getForInSta($payarr);
              $where .=" and orderid in (".$sum1.")";
              $where .= " and status = 6";
          }
          $ww = "1=1";
          $ww .= " and status = -1";
          $ww .= " and create_time < ".$jt;
          $arra = $order->where($ww)->select();
          $zfc  = $this->getForInSta($arra);
          if($zfc){
            $where .=" and orderid not in (".$zfc.")";  
          }
          $res =  $order->where($where)->limit($index[0],$index[1])->select();
          $count1 = count($res);
          for($i = 0; $i < $count1; $i++){
              if($sum1){
                  $sum1.=",'".$res[$i]['uid']."'";
              }else{
                  $sum1.="'".$res[$i]['uid']."'";
              }
              if($sum2){
                  $sum2.=",'".$res[$i]['carnum']."'";
              }else{
                  $sum2.="'".$res[$i]['carnum']."'";
              }
          }
          $m   ="1=1";
          $m  .=" and id in (".$sum1.")";
          $ma  ="1=1";
          $ma .=" and carnum in (".$sum2.")";
          $useradd = $user->where($m)->field('id,nickname,tel,waynum')->select();
          $carsadd = $cars->where($ma)->field('name,carnum,type')->select();
          foreach ($res as $key => $value) {
              foreach ($useradd as $ke => $va) {
                  if($value['uid'] == $va['id']){
                      $res[$key]['nickname'] = $va['nickname'];
                  }
              }
              foreach ($carsadd as $k => $v) {
                  if($v['carnum'] == $value['carnum']){
                      $res[$key]['name'] = $v['name'];
                      $res[$key]['first_pay'] = $v['first_pay'];
                      $res[$key]['guide_price'] = $v['guide_price'];
                      $res[$key]['type'] = $v['type'];
                  }
              }
          }
          return $res;
      }
    }
    /**
     * 拼接字符串查找条件
     */
    public function getForInSta($sum){
        $count = count($sum);
        for($i = 0; $i < $count; $i++){
            if($s){
                $s.=",'".$sum[$i]['orderid']."'";
            }else{
                $s.="'".$sum[$i]['orderid']."'";
            }
        }
        return $s;
    }
    /**
     * 查看详细和确认详细jdc_cars_stock
     */
    public function  getPublicSign($data){
        $user       = M('user');
        $price_db   = M('price');//价格表
        $order      = M('order');
        $cars       = M('cars');
        $carscolour = M('cars_stock');
        $jdcstock   = M('stock');//库存所在地
        $city       = M('city');
        $admin      = M('admin');
        $operation  = M('order_operation');
        $stockdetails_db  = M('stock_details');
        //找到订单
        $order_arr = $order->where(array('orderid'=>$data['orderid']))->find();
        $kucun     = $carscolour->where(array('id'=>$order_arr['stockid']))->find();
        $colours   = $kucun['color'];
        $stockku   = $jdcstock->where(array('id'=>$kucun['sid']))->find();
        //查找车架号
        $framenumber = $stockdetails_db->where(array('stock_id'=>$kucun['id'],'status'=>1))->select();
        $cityadd   = $city->where(array('id'=>$order_arr['cityid']))->field('name,pid')->find();
        $citypid   = $city->where(array('id'=>$cityadd['pid']))->field('name')->find();
        $soketid   = $city->where(array('id'=>$kucun['cityid']))->field('name')->find();
        $wehre  ='1=1';
        $wehre .= ' and orderid ='.$data['orderid'];
        $wehre .= ' and status = 0';
        $resadd = $operation->where($wehre)->find();
        $adminarr  = $admin->where(array('usernum'=>$resadd['usernum']))->field('name,usernum')->find();
        $user_arr  = $user->where(array('id'=>$order_arr['uid']))->find();
        $cars_arr  = $cars->where(array('carnum'=>$order_arr['carnum']))->field('carnum,name,first_pay,guide_price,brand,type,region_id,month_pay,type,details,jdc_price')->find();
        if($order_arr['create_time'] >  1527838056){
           $priceversion    = $price_db->where(array('id'=>$order_arr['price_version_id']))->field('month_pay,first_pay,pay_month,insurance,surplus_money')->find();
           $cars_arr['month_pay'] = $priceversion['month_pay'];
           $cars_arr['first_pay'] = $priceversion['first_pay'];
        }
        $raadd = array(
                "orderid"     => $order_arr['orderid'],//订单编号
                "adminname"   => $adminarr['name'],  //顾问姓名
                "adminnum"    => $adminarr['usernum'],  //顾问ID
                "create_time" => date('Y-m-d H:i',$order_arr['create_time']),  //创建时间
                "waynum"      => $user_arr['waynum'],  //渠道推荐码
                "savename"    => $citypid['name'],  //所属省份
                "cityname"    => $cityadd['name'],  //所属城市
                "carnum"      => $cars_arr['carnum'],  //车辆编号
                "carsname"    => $cars_arr['name'],  //车辆名称
                "brand"       => $cars_arr['brand'],  //品牌
                "cartype"     => $cars_arr['type'],  //车辆类型/款式
                "colors"      => $colours,          //颜色
                "guide_price" => $cars_arr['guide_price'],  //车辆价格
                "first_pay"   => $cars_arr['first_pay'],  //首付
                "month_pay"   => $cars_arr['month_pay'],  //月供
                "nickname"    => $user_arr['nickname'],  //客户姓名
                "tel"         => $user_arr['tel'],  //注册手机号
                "details"     => $cars_arr['details'],  //汽车信息
                "soket"       => $stockku['city'],  //库存所在地
                "banknum"     => $user_arr['banknum'],  //银行卡号
                "framenumber" => $framenumber,  //车架号
            );
        return $raadd;
    }

    /**
     * 修改库存和插入出库数据
     */
    public function setStockDelete($data){
        $stockdetails_db    = M('stock_details');//车辆详情
        $carsstock_db       = M('cars_stock');//车辆库存数
        $caroperation_db    = M('car_operation');//车辆记录表
        $stockoperation_db  = M('stock_operation');//采购记录表
        $stockdeta = $stockdetails_db->where(array('id'=>$data['id'],'framenum'=>$data['framesizes'],'enginenum'=>$data['enginelist']))->find();
        if($stockdeta['status'] != 1){
           $this->ajaxReturn(array('ret'=>0,"msg"=>"对不起该发动机车辆刚已卖出!"));
        }
        $carfindres = $carsstock_db->where(array('id'=>$stockdeta['stock_id']))->find();
        if($carfindres['stock'] >= 1){
            $carres     = $carsstock_db->where(array('id'=>$stockdeta['stock_id']))->setDec('stock');
            $resid      = $stockdetails_db->where(array('id'=>$stockdeta['id']))->save(array('status'=>0));
            $num        = $carsstock_db->where(array('sid'=>$carfindres['sid'],'carnum'=>$carfindres['carnum']))->sum('stock');
              //添加采购
            $stock_operation_data=[];
            $stock_operation_data['orderid']        = $data['orderid'];
            $stock_operation_data['sid']            = $carfindres['sid'];
            $stock_operation_data['type']           = 2;
            $stock_operation_data['carnum']         = $carfindres['carnum'];
            $stock_operation_data['num']            = 1;
            $stock_operation_data['stocknum']       = $num;
            if(session('lampzuo_id')){
                $stock_operation_data['admin_id']   = session('lampzuo_id');
            }
            $stock_operation_data['operation_time'] = time();
            $stock_operation_data['create_time']    = time();
            $pid = $stockoperation_db->add($stock_operation_data);
            if($pid){
              $car_operation_data=[];
              $car_operation_data['type']          = 2;
              $car_operation_data['carnum']        = $carfindres['carnum'];
              $car_operation_data['color']         = $carfindres['color'];
              $car_operation_data['pid']           = $pid;
              $car_operation_data['stock_id']      = $stockdeta['stock_id'];
              $car_operation_data['details_id']    = $stockdeta['id'];
              if(session('lampzuo_id')){
                  $car_operation_data['admin_id']  = session('lampzuo_id');
              }
              $car_operation_data['operation_time']= time();
              $car_operation_data['stocknum']      = 1;
              $car_operation_data['create_time']   = time();
              $carcheliangdata = $caroperation_db->add($car_operation_data);
              if($carcheliangdata){
                return true;
              }else{
                return false;
              }
            }
        }else{
          return array('success'=>'ERROR','msg'=>"该车库存不足");
        }
        
    }
    /**
     * 确认签约处理
     */
    public function getQianYue($data){
      $order    = M('Order');
      $admin    = M('admin');
      $carsco   = M('cars_stock');
      $user     = M('user');
      $waypay   = M('wayuser_pay');
      $wayuser  = M('wayuser');
      $seid     = $_SESSION['lampzuo_id'];
      $adminli  = $admin->where(array('id'=>$seid))->find();
      if(!$adminli){
        $this->ajaxReturn(array('msg'=>40001));
      }
      $orderoperation = M('order_operation');
      $userArr = array(
                "orderid" => $data['orderid'],
                "usernum" => $adminli['usernum'],
                "status"  => 3,
                "remark"  => "签约订单",
                "create_time"=> time(),
              );
      $wayt  = $order->where(array('orderid'=>$data['orderid']))->find();
      $usert = $user->where(array('id'=>$wayt['uid']))->find();

      if($data['banknum'] && $data['withholdphone']){
          $usert['banknum'] = $data['banknum'];
          $usert['tel'] = $data['withholdphone'];
          $resuser  =  $user->where(array('id'=>$usert['id']))->save(array('banknum'=>$data['banknum'],'reserve_tel'=>$data['withholdphone']));
      }
      $userdata =[
        'orderId'=>$data['orderid'],//订单号
        'phoneNo'=>$usert['tel'],//电话号码
        'accNo'=>$usert['banknum'],//银行卡号
        'certifId'=>$usert['identify'],//身份证号码
        'customerNm'=>$usert['fullanme']//姓名
        ];
      //银行卡代扣授权是否成功
      // $addwarr = Warrant($userdata);
      $addwarr = '1';
      if($addwarr == "0"){
        return ['withhold'=>"ERROR",'msg'=>"代扣银行授权失败"];die;
      }else{
        $resdata = $this->setStockDelete($data);
        if($resdata['success'] == "ERROR"){
          return ['success'=>"ERROR",'msg'=>$resdata['msg']];die;
        }
      }

      //渠道分润
      $wayarr = array();
      if($usert['waynum']){
        $res = $wayuser->where(array('waynum'=>$usert['waynum'],'status'=>2))->find();
        $waynummoney = $res['channeltype'] == 1 ? self::INTOPRICE:self::INTOP;
        if($res){
            $wayarr = array(
              'orderid'=>$data['orderid'],
              'waynum'=>$usert['waynum'],
              'usernum'=>$adminli['usernum'],
              'money'=>$waynummoney,
              'status'=>0,
              'create_time'=>time(),
            );
        }
      }
      $orderArr = array(  
                'status'=> 3,
                'remark'=>"签约",
                'contract'=>$data['contract'],
                'framenum'=>$data['framesizes'],
                'enginenum'=>$data['enginelist'],
                );
      $res      =  $order->where(array('orderid'=>$data['orderid']))->save($orderArr);
      if($res){
          $orderoperation->add($userArr);
          $waypay->add($wayarr);
          $aares      =  $order->where(array('orderid'=>$data['orderid']))->find();
          $carstock   = $carsco->where(array('id'=>$aares['stockid']))->find();
          return true;
      }else{
          return false;
      }
    }
    /**
     * 确认上牌处理
     */
    public function getShangPai($data){
      $order    = M('Order');
      $orderpay = M('order_pay');
      $admin    = M('admin');
      $seid     = $_SESSION['lampzuo_id'];
      $adminli  = $admin->where(array('id'=>$seid))->find();
      if(!$adminli){
        $this->ajaxReturn(array('msg'=>40001));
      }
      $orderoperation = M('order_operation');
      $userArr = array(
                "orderid" => $data['orderid'],
                "usernum" => $adminli['usernum'],
                "status"  => 5,
                "remark"  => "上牌",
                "create_time"=> time(),
        );
      $orderArr = array(
                  'status'=> 5,
                  'remark'=>"上牌",
                  'car_num'=>$data['carnum'],
                  );
      $res      =  $order->where(array('orderid'=>$data['orderid']))->save($orderArr);
      if($res){
          $orderoperation->add($userArr);
          return true;
      }else{
          return false;
      }
    }
    /**
     * 状态信息状态(-2代表暂拒可重新申请订单，-1被拒订单，0才创建的订单，1风控已审核通过订单，2城市经理人审核通过订单，3用户已签约，4确认收款,5代表车辆已上牌，6代表交易完成订单,)
     */
    public function getModelStatus($data){
            $res = $data;
            foreach ($res as $key => $value) {
                  $res[$key]['create_time'] = date('Y-m-d H:i:s',$value['create_time']);
                  if($value['status'] == "0"){
                    $res[$key]['addstatus'] = "等待审核(风控)";
                  }elseif ($value['status'] == "2") {
                    $res[$key]['addstatus'] = "等待签约";
                  }elseif ($value['status'] == "3") {
                    $res[$key]['addstatus'] = "等待收款";
                  }elseif ($value['status'] == "4") {
                    $res[$key]['addstatus'] = "等待上牌";
                  }elseif ($value['status'] == "5") {
                    $res[$key]['addstatus'] = "等待提车";
                  }elseif ($value['status'] == "6") {
                    $res[$key]['addstatus'] = "已交付订单";
                  }elseif ($value['status'] == "-1") {
                    $res[$key]['addstatus'] = "拒单";
                  }elseif ($value['status'] == "-2") {
                    $res[$key]['addstatus'] = "订单驳回";
                  }elseif ($value['status'] == "7") {
                    $res[$key]['addstatus'] = "等待审核(风控)";
                  }elseif ($value['status'] == "1") {
                    $res[$key]['addstatus'] = "等待审核(经理)";
                  }       
            }
            return $res;
    }
    /**
     * 订单管理显示数据
     */
    public function getAdminOrderList($data){
        $admin = M('admin');
        $order = M('order');
        $myinfo_db = D('Myinfo');
        $field = ['usernum','insert_time','id','position','tel','name'];
        $myinfo_data = $myinfo_db->getinfofield(['id'=>session('lampzuo_id')],$field);
        $orderpay = M('order_month_pay');
        $orderoperation = M('order_operation');
        $res   = $admin->where(array('id'=>$data))->find();
        $arr   = array(
            'toorder' => 0,
            'shenheorder' => 0,
            'hangorder' => 0,
            'signorder' => 0,
            'countorder' => 0,
            'complete' => 0,
            'yuqi' => 0,
            'adminname'=>$res['name'],
            'admintel'=>$res['tel'],
            'benyue_danshu'=>$myinfo_data['benyue_danshu'],
            'benyuechenggong'=>$myinfo_data['benyuechenggong'],
            'benyue_beiju'=>$myinfo_data['benyue_beiju'],
            );
        if($res['position'] == 1){
            $m['status']  = array('EQ',0);
            $m['usernum'] = array('EQ',$res['usernum']);
            $resaa =  $orderoperation->where($m)->field('orderid')->select();
            $sum = $this->getForInSta($resaa);
            $where  ="1=1";
            $where .=" and orderid in (".$sum.")";
            $where .=" and status <> 6";
            $arra   = $order->where($where)->select();
            $res = array();
            foreach ($arra as $key => $value) {
                $jt=strtotime(date("Y-m-d",strtotime("-1 day")).' 23:59:59');
                if($value['status'] == '-1'){
                    if($value['create_time'] < $jt){
                         unset($arra[$key]);  
                    }
                }
                if ($arra[$key] != null) {
                    array_push($res,$arra[$key]);
                }
            }
            $resadd = count($res);//未完成
            $arr['toorder'] += $resadd;
            $m  = "1=1";
            $m .=" and orderid in (".$sum.")";
            $m .=" and status in ('0','1','7')";
            $arr['shenheorder'] += $order->where($m)->count();//待审订单
           
            $l  = "1=1";
            $l .=" and orderid in (".$sum.")";
            $l .=" and status >= 2";
            $l .=" and status < 4";
            $arr['hangorder'] += $order->where($l)->count();//未签约订单
            $a  = "1=1";
            $a .=" and orderid in (".$sum.")";
            $a .=" and status = 4";
            $arr['signorder'] += $order->where($a)->count();//已签约订单||等待上牌订单
            $b  = "1=1";
            $b .=" and orderid in (".$sum.")";
            $b .=" and status = 5";
            $arr['complete']  += $order->where($b)->count();//完成上牌订单||等待提车订单
            $c  = "1=1";
            $c .=" and orderid in (".$sum.")";
            $c .=" and status = 6";
            $arr['countorder'] += $order->where($c)->count();//累计完成订单
            $tiems = time();
            $d  = "1=1";
            $d .=" and orderid in (".$sum.")";
            $d .= " and status = 6";
            $arryuqi = $order->where($d)->select();
            $sum11 = $this->getForInSta($arryuqi);
            $sd    = "1=1";
            $sd   .=" and orderid in (".$sum11.")";
            $sd   .=" and pay_time <= ".$tiems;
            $sd   .=" and status <> 1";
            $orpaycount   = $orderpay->where($sd)->group('orderid')->select();//逾期单数
            if($orpaycount){
                 $arr['yuqi'] += count($orpaycount);//逾期单数
            }
            $date = date('Y-m-d');
            $benyue_a = date('Y-m-01 00:00:00', strtotime($date));
            $benyue_z = strtotime(date('Y-m-d 23:59:59', strtotime("$benyue_a +1 month -1 day")));
            $benyue_a = strtotime($benyue_a);
            $e  = "1=1";
            $e .=" and orderid in (".$sum.")";
            $e .=" and create_time > ".$benyue_a;
            $e .=" and create_time < ".$benyue_z;
            $e .=" and status = 6";
            $arr['benyue'] += $order->where($e)->count();
            //全部
            $s  = "1=1";
            $s .=" and orderid in (".$sum.")";
            $arr['quanbu'] += $order->where($s)->count();
            if($arr['quanbu'] > 0){
                $arr['tongguo'] =  $arr['countorder'] / $arr['quanbu'] * 100;
                $arr['tongguo'] = round($arr['tongguo'],2);
            }else{
                $arr['tongguo'] = 0;
            }
            
            return $arr;
        }elseif ($res['position'] == 3) {
            
            // $where .= " and cityid = ".$res['cityid'];
            $admin  = M("admin");
            $orderoperation = M("order_operation");
            $ww    = "1=1";
            $ww   .= " and pid = ".$res['id'];
            $resdata =  $admin->where($ww)->select();
            $count1 = count($resdata);
            for($i = 0; $i < $count1; $i++){
                if($sum2){
                    $sum2.=",'".$resdata[$i]['usernum']."'";
                }else{
                    $sum2.="'".$resdata[$i]['usernum']."'";
                }
            }
            $wdecityid   = "1=1"; 
            $wdecityid  .= " and status = 0"; 
            $wdecityid  .= " and usernum in (".$sum2.")"; 
            $citydata    =  $orderoperation->where($wdecityid)->field('orderid')->select();
            $arrorder    = $this->getForInSta($citydata);
            $where  = "1=1";
            $where .=" and status <> 6";
            $where .=" and status <> -1";
            $where .=" and orderid in (".$arrorder.")";
            $arr['toorder'] +=  $order->where($where)->count();//未完成
            $m  = "1=1";
            // $m .= " and cityid = ".$res['cityid'];
            $m .=" and orderid in (".$arrorder.")";
            $m .=" and status in ('0','1','7')";
            $arr['shenheorder'] += $order->where($m)->count();//待审订单
            $l  = "1=1";
            // $l .= " and cityid = ".$res['cityid'];
            $l .=" and orderid in (".$arrorder.")";
            $l .=" and status >= 2";
            $l .=" and status < 4";
            $arr['hangorder'] += $order->where($l)->count();//未签约订单
            $a  = "1=1";
            // $a .= " and cityid = ".$res['cityid'];
            $a .=" and orderid in (".$arrorder.")";
            $a .= " and status = 4";
            $arr['signorder'] += $order->where($a)->count();//已签约订单||等待上牌订单
            $b  = "1=1";
            // $b .= " and cityid = ".$res['cityid'];
            $b .=" and orderid in (".$arrorder.")";
            $b .=" and status = 5";
            $arr['complete']  += $order->where($b)->count();//完成上牌订单||等待提车订单
            $c  = "1=1";
            // $c .= " and cityid = ".$res['cityid'];
            $c .=" and orderid in (".$arrorder.")";
            $c .=" and status = 6";
            $arr['countorder'] += $order->where($c)->count();//累计完成订单
            $tiems = time();
            $d  = "1=1";
            // $d .= " and cityid = ".$res['cityid'];
            $d .=" and orderid in (".$arrorder.")";
            $d .= " and status = 6";
            $arryuqi = $order->where($d)->select();
            $sum11 = $this->getForInSta($arryuqi);
            $sd   = "1=1";
            $sd  .=" and orderid in (".$sum11.")";
            $sd  .=" and pay_time <= ".$tiems;
            $sd  .=" and status <> 1";
            $orpaycount   = $orderpay->where($sd)->group('orderid')->select();//逾期单数
            if($orpaycount){
                 $arr['yuqi'] += count($orpaycount);//逾期单数
            }
            $date = date('Y-m-d');
            $benyue_a = date('Y-m-01 00:00:00', strtotime($date));
            $benyue_z = strtotime(date('Y-m-d 23:59:59', strtotime("$benyue_a +1 month -1 day")));
            $benyue_a = strtotime($benyue_a);
            $e  ="1=1";
            // $e .=" and cityid = ".$res['cityid'];
            $e .=" and orderid in (".$arrorder.")";
            $e .=" and orderid in (".$sum11.")";
            $e .=" and create_time > ".$benyue_a;
            $e .=" and create_time < ".$benyue_z;
            $e .=" and status = 6";
            $arr['benyue'] += $order->where($e)->count();//本月完成单
            //全部
            $s  = "1=1";
            // $s .=" and orderid in (".$sum11.")";
            $s .=" and orderid in (".$arrorder.")";
            $arr['quanbu'] += $order->where($s)->count();
            if($arr['quanbu'] > 0){
                $arr['tongguo'] =  $arr['countorder'] / $arr['quanbu'] * 100;
                $arr['tongguo'] = round($arr['tongguo'],2);
            }else{
                $arr['tongguo'] = 0;
            }
            return $arr;
        }elseif ($res['position'] == 4) {
            $where  = "1=1";
            $where .= " and provinceid = ".$res['provinceid'];
            $where .= " and status <> 6";
            $where .= " and status <> -1";
            $arr['toorder'] +=  $order->where($where)->count();//未完成
            $m  = "1=1";
            $m .= " and provinceid = ".$res['provinceid'];
            $m .=" and status in ('0','1','7')";
            $arr['shenheorder'] += $order->where($m)->count();//待审订单
            $l  = "1=1";
            $l .= " and provinceid = ".$res['provinceid'];
            $l .=" and status >= 2";
            $l .=" and status < 4";
            $arr['hangorder'] += $order->where($l)->count();//未签约订单
            $a  = "1=1";
            $a .= " and provinceid = ".$res['provinceid'];
            $a .= " and status = 4";
            $arr['signorder'] += $order->where($a)->count();//已签约订单||等待上牌订单
            $b  = "1=1";
            $b .= " and provinceid = ".$res['provinceid'];
            $b .=" and status = 5";
            $arr['complete']  += $order->where($b)->count();//完成上牌订单||等待提车订单
            $c  = "1=1";
            $c .= " and provinceid = ".$res['provinceid'];
            $c .=" and status = 6";
            $arr['countorder'] += $order->where($c)->count();//累计完成订单
            $tiems = time();
            $d  = "1=1";
            $d .= " and provinceid = ".$res['provinceid'];
            $d .= " and status = 6";
            $arryuqi = $order->where($d)->select();
            $sum11 = $this->getForInSta($arryuqi);
            $sd   = "1=1";
            $sd  .=" and orderid in (".$sum11.")";
            $sd  .=" and pay_time <= ".$tiems;
            $sd  .=" and status <> 1";
            $orpaycount   = $orderpay->where($sd)->group('orderid')->select();//逾期单数
            if($orpaycount){
                 $arr['yuqi'] += count($orpaycount);//逾期单数
            }
           
            $date = date('Y-m-d');
            $benyue_a = date('Y-m-01 00:00:00', strtotime($date));
            $benyue_z = strtotime(date('Y-m-d 23:59:59', strtotime("$benyue_a +1 month -1 day")));
            $benyue_a = strtotime($benyue_a);
            $e  = "1=1";
            $e .=" and orderid in (".$sum11.")";
            $e .=" and provinceid = ".$res['provinceid'];
            $e .=" and create_time > ".$benyue_a;
            $e .=" and create_time < ".$benyue_z;
            $e .=" and status = 6";
            $arr['benyue'] += $order->where($e)->count();//本月完成单
            //全部
            $s  = "1=1";
            $s .=" and orderid in (".$sum11.")";
            $arr['quanbu'] += $order->where($s)->count();
            if($arr['quanbu'] > 0){
                $arr['tongguo'] =  $arr['countorder'] / $arr['quanbu'] * 100;
                $arr['tongguo'] = round($arr['tongguo'],2);
            }else{
                $arr['tongguo'] = 0;
            }
            return $arr;
        }elseif ($res['position'] == 1100){
            $where  = "1=1";
            // $where .= " and provinceid = ".$res['provinceid'];
            $where .= " and status <> 6";
            $where .= " and status <> -1";
            $arr['toorder'] +=  $order->where($where)->count();//未完成
            $m  = "1=1";
            $m .=" and status in ('0','1','7')";
            $arr['shenheorder'] += $order->where($m)->count();//待审订单
            $l  = "1=1";
            $l .=" and status >= 2";
            $l .=" and status < 4";
            $arr['hangorder'] += $order->where($l)->count();//未签约订单
            $a  = "1=1";
            $a .= " and status = 4";
            $arr['signorder'] += $order->where($a)->count();//已签约订单||等待上牌订单
            $b  = "1=1";
            $b .=" and status = 5";
            $arr['complete']  += $order->where($b)->count();//完成上牌订单||等待提车订单
            $c  = "1=1";
            $c .=" and status = 6";
            $arr['countorder'] += $order->where($c)->count();//累计完成订单
            $tiems = time();
            $d  = "1=1";
            $d .= " and status = 6";
            $arryuqi = $order->where($d)->select();
            $sum11 = $this->getForInSta($arryuqi);
            $sd   = "1=1";
            $sd  .=" and orderid in (".$sum11.")";
            $sd  .=" and pay_time <= ".$tiems;
            $sd  .=" and status <> 1";
            $orpaycount   = $orderpay->where($sd)->group('orderid')->select();//逾期单数
            if($orpaycount){
                 $arr['yuqi'] += count($orpaycount);//逾期单数
            }
            $date = date('Y-m-d');
            $benyue_a = date('Y-m-01 00:00:00', strtotime($date));
            $benyue_z = strtotime(date('Y-m-d 23:59:59', strtotime("$benyue_a +1 month -1 day")));
            $benyue_a = strtotime($benyue_a);
            $e  = "1=1";
            $e .=" and orderid in (".$sum11.")";
            $e .=" and create_time > ".$benyue_a;
            $e .=" and create_time < ".$benyue_z;
            $e .=" and status = 6";
            $arr['benyue'] += $order->where($e)->count();//本月完成单
            //全部
            $s  = "1=1";
            $s .=" and orderid in (".$sum11.")";
            $arr['quanbu'] += $order->where($s)->count();
            if($arr['quanbu'] > 0){
                $arr['tongguo'] =  $arr['countorder'] / $arr['quanbu'] * 100;
                $arr['tongguo'] = round($arr['tongguo'],2);
            }else{
                $arr['tongguo'] = 0;
            }
            
            return $arr;
        }
    }

    /**
     * 统计订单
     * $id 查询条件
     * $type 
     */
    public function OrderCount($id,$type) {
        $order_mdb = M('order');
        if($type=='chenggong'){
            $order_count = $order_mdb->where($id)->where('status=6')->count();
            return $order_count;
        }else if($type=='benyue_chenggong'){
            $date = date('Y-m-d');
            $benyue_a = date('Y-m-01 00:00:00', strtotime($date));
            $benyue_z = strtotime(date('Y-m-d 23:59:59', strtotime("$benyue_a +1 month -1 day")));
            $benyue_a = strtotime($benyue_a);
            $order_count = $order_mdb->where($id)->where('status=6 and create_time<'.$benyue_z.' and create_time>'.$benyue_a)->count();
            return $order_count;
        }
    }

    /**
     * 查询订单关联数据
     */
    public function OrderIndexAdmin($orderid,$field=false,$status=false) {
        $orderOperation_mdb = M('order_operation');
        switch ($field) {
            case 'adminname':
                $order_data = $orderOperation_mdb->where('orderid='.$orderid.' and status=0')->find();
                $admin_db = D('admin');
                $admin_data = $admin_db->where(array("usernum"=>$order_data['usernum']))->find();
                return $admin_data;
                break;
            case 'wayinfo':
                $user_db = M('user');
                $waynum_db = M('wayuser');
                $userinfo = $user_db->where('id='.$orderid)->field('waynum,id')->find();
                $way_data = $waynum_db->where(array('waynum'=>$userinfo['waynum']))->field('waynum,status')->find();
                return $way_data;
            case 'actionshijian':
                if($status)
                $order_data = $orderOperation_mdb->where('orderid='.$orderid.' and '.$status)->find();
                return $order_data;
                break;
            default:
                
                break;
        }
    }

    /**
     * 风控审核通过订单
     */
    public function getSiskEvaluate($data){
          $order    = M('Order');
          $orderpay = M('order_pay');
          $admin    = M('admin');
          $seid     = $_SESSION['lampzuo_id'];
          $adminli  = $admin->where(array('id'=>$seid))->find();
          $order_res = $order -> field('jdc_cars.jdc_price') -> join('jdc_cars on jdc_cars.carnum=jdc_order.carnum') ->where('orderid='.$data['orderid']) -> find();
          if(!$adminli){
            $this->ajaxReturn(array('msg'=>40001));
          }
          if($data['status'] != 1){
            $status = $data['status'];
            $data['auditor'] = 0;
            $data['thirdparty_audit'] = 0;
          }
          if ($data['status'] == 1 && $adminli['position'] == 5) {
              $data['auditor'] = 1;//审核员审
              $data['status']  = 0;
              $status = 1;
          } else if ($data['status'] == 1 && $adminli['position'] == 501 && $order_res['jdc_price'] <= 150000) {
              $data['status']  = 1;//15w以下主管审核通过
              $data['auditor'] = 2;
          }else if ($data['status'] == 1 && $adminli['position'] == 501 && $order_res['jdc_price'] >= 150000) {
              $data['auditor'] = 2;//15w以上主管审
              $data['status']  = 0;
              $status = 1;
          }else if ($data['status'] == 1 && $adminli['position'] == 502) {
              $data['status']  = 0;//15w以上主管审核通过
              $data['auditor'] = 3;
              $data['thirdparty_audit'] = 1;
              $status = 1;
          }else if ($data['status'] == 1 && $adminli['position'] == 503) {
              $data['status']  = 1;//最终第三方审核通过
              $data['auditor'] = 4;
              $data['thirdparty_audit'] = 2;
              $status = 1;
          }
          $orderoperation = M('order_operation');
          $userArr = array(
                    "orderid" => $data['orderid'],
                    "usernum" => $adminli['usernum'],
                    "status"  => $status,
                    "remark"  => $data['reject_remark'],
                    "create_time"=> time(),
          );
          if ($adminli['position'] == 5) {
              $orderArr = array('status'=> $data['status'],"auditor" => $data['auditor'],'remark'=>"风控审核");
          } else if ($adminli['position'] == 501) {
              $orderArr = array('status'=> $data['status'],"auditor" => $data['auditor'],'remark'=>"风控主管审核");
          }else if ($adminli['position'] == 502) {
              $orderArr = array('status'=> $data['status'],"auditor" => $data['auditor'],"thirdparty_audit" => $data['thirdparty_audit'],'remark'=>"风控经理审核");
          }else if ($adminli['position'] == 503) {
              $orderArr = array('status'=> $data['status'],"auditor" => $data['auditor'],"thirdparty_audit" => $data['thirdparty_audit'],'remark'=>"第三方审核");
          }
          $res      =  $order->where(array('orderid'=>$data['orderid']))->save($orderArr);
          if($res){
              $orderoperation->add($userArr);
              return $order_res;
          }else{
              return false;
          }
    }

    /**
     * 财务确认收款操作
     */
    public function getFinance($data){
        $order    = M('Order');
        $price_db = M('price');
        $Cars     = M('Cars');
        $or       = M('order_operation');
        $orderpay = M('order_pay');
        $admin    = M('admin');
        $monthpay = D('MonthPay');
        $res      = $order->where(array('orderid'=>$data['orderid']))->find();
        if($res['status']!='3'){
          return "2";
        }
        $price = $price_db->where(['id'=>$res['price_version_id'],'version'=>$res['price_version']])->find();
        // echo "<pre>";
        // print_r($price);die;
        $Carsres  = $Cars->where(array('carnum'=>$data['carnum']))->field('carnum,guide_price,first_pay,month_pay,zz_month_pay')->find();
        $seid     = session('lampzuo_id');
        $adminli  = $admin->where(array('id'=>$seid))->find();
        if($adminli == ""){
            return "1";
        }else if($adminli['position'] != 6){
            return '6';
        }

        $arr = array(
                "orderid"=> $res['orderid'],
                "uid"=> $res['uid'],
                "usernum" => $adminli['usernum'],
                "is_down_pay"=> 1,//是否是首付,1是,0否
                'status'=>1,
                'pay_month' => 1,
                "next_pay"=> $price['month_pay'],
                "money"=> $price['first_pay'],
                "paymoney"=> $price['first_pay'],
                "price_version_id"=> $price['id'],
                "create_time"=>time(),
            );
        $arrfirst = array(
                  "orderid"=> $res['orderid'],
                  "uid"=> $res['uid'],
                  "usernum" => $adminli['usernum'],
                  "is_down_pay"=> 0,//是否是首付,1是,0否
                  'status'=>1,
                  'pay_month' => 1,
                  "next_pay"=> $price['month_pay'],
                  "money"=> $price['month_pay'],
                  "price_version_id"=>$price['id'],
                  "paymoney"=> $price['first_pay']+$price['month_pay']+$price['zz_month_pay'],
                  "create_time"=>time(),
              );
        $userArr = array(
                    "orderid" => $data['orderid'],
                    "usernum" => $adminli['usernum'],
                    "status"  => 4,
                    "remark"  => "财务确认收款",
                    "create_time"=> time(),
            );
        $orderArr = array('status'=>4,'remark'=>"财务确认收款");
        $result      =  $order->where(array('orderid'=>$data['orderid']))->save($orderArr);
        if($result){
           $arrid = $orderpay->add($arr);
           if($arrid){
              $orderpay->add($arrfirst);
              $monthpay->addMonthPay($res['orderid'],$price['month_pay'],$price['zz_month_pay']);
              $or->add($userArr);
           }
            return true;
        }else{
            return false;
        }
    }
    /**
     * 显示未分润渠道
     */
    public function getWaynumMoney(){
        $order_mdb = M('order');
        $orderPay_mdb  = M('order_pay');
        $orderOper_mdb = M('order_operation');
        $user_mdb    = M('user');
        $wayuser_pay = M('wayuser_pay');
        $wayuser     = M('wayuser');
        $orderres = $orderOper_mdb->where(array('status'=>4))->select();
        $listwaynu = implode(',',array_column($orderres, 'orderid'));
        $where  = " and orderid in (".$listwaynu.")";
        $where  .= " and status = 0";
        $wayarr = $wayuser_pay->where("1=1".$where)->select();
        $listwaunum = implode(',',array_column($wayarr, 'waynum'));
        $w  = " and waynum in (".$listwaunum.")";
        $userway = $wayuser->where("1=1".$w)->select();
        foreach ($wayarr as $key => $value) {
          foreach ($userway as $ke => $va) {
              if($value['waynum'] == $va['waynum']){
                  $wayarr[$key]['bank'] = $va['bank'];
                  $wayarr[$key]['banker'] = $va['banker'];
                  $wayarr[$key]['banknum'] = $va['banknum'];
                  $wayarr[$key]['admin_id'] = $va['admin_id'];
                  $wayarr[$key]['occupation'] = $va['occupation'];
                  $wayarr[$key]['waynum'] = $va['waynum'];
                  $wayarr[$key]['age'] = $va['age'];
                  $wayarr[$key]['Waystatus'] = $va['status'];
                  $wayarr[$key]['name'] = $va['name'];
              }
          }
        }
        return $wayarr;
    }
    /**
     * 显示已分润操作记录
     */
    public function getWaynumList($data){
      $admin  = M("admin");
      $wayuser_pay = M('wayuser_pay');
      $waynum = M('wayuser');
      $addres = $admin->where(array('id'=>$data))->find();
      $where  = "1=1";
      // $where .= " and usernum = ('".$addres['usernum']."')";
      $where .= " and status = 1";
      $wayarr = $wayuser_pay->where($where)->select();
      $listwaynu = implode(',',array_column($wayarr, 'waynum'));
      $w   = " and waynum in (".$listwaynu.")";
      $userway = $waynum->where("1=1".$w)->select();
      foreach ($wayarr as $key => $value) {
        foreach ($userway as $ke => $va) {
            if($value['waynum'] == $va['waynum']){
                $wayarr[$key]['bank'] = $va['bank'];
                $wayarr[$key]['banker'] = $va['banker'];
                $wayarr[$key]['banknum'] = $va['banknum'];
                $wayarr[$key]['admin_id'] = $va['admin_id'];
                $wayarr[$key]['occupation'] = $va['occupation'];
                $wayarr[$key]['waynum'] = $va['waynum'];
                $wayarr[$key]['age'] = $va['age'];
                $wayarr[$key]['Waystatus'] = $va['status'];
                $wayarr[$key]['name'] = $va['name'];
                // $wayarr[$key]['usertypename'] = $addres['name'];
            }
        }
      }
      $count = count($wayarr);
      for($i = 0; $i < $count; $i++){
          if($wx){
              $wx.=",'".$wayarr[$i]['usernum']."'";
          }else{
              $wx.="'".$wayarr[$i]['usernum']."'";
          }
      }
      $userwx   .= " and usernum in (".$wx.")";
      $unameway = $admin->where("1=1".$userwx)->select();
      foreach ($wayarr as $key => $value) {
        foreach ($unameway as $k => $v) {
          if($value['usernum'] ==  $v['usernum']){
            $wayarr[$key]['username'] = $v['name'];
          }
        }
      }
      
      return $wayarr;
     
    }

    public function getDates($start = 1, $end = 12)
    {
        $date = [];
        $m = date('m', time());
        $y = date('Y', time());
        $m = $m - $start + 1;
        if ($m <= 0) {
            $m = 12 + $m;
            $y = $y - 1;
        }
        $currtime = strtotime($this -> get_y_m_d($y, $m));
        $count = $end - $start;
        for ($i = 0; $i <= $count; $i++) {
            $date[$i] = date('Y-m', $currtime);
            $d = date('d', $currtime);
            $time = $currtime - (60*60*24*$d);
            $currtime = $time;
        }
        return $date;
    }

    public function get_y_m_d($y, $m)
    {
        if( in_array($m , array(1, 3, 5, 7, 8, 01, 03, 05, 07, 10, 12)))
        {
            // $text = $year.'年的'.$month.'月有31天';
            $text = '31';
        }
        elseif( $m == 2 )
        {
            if ( $y % 400 == 0  || ($y % 4 == 0 && $y % 100 !== 0) )        //判断是否是闰年
            {
                // $text = $year.'年的'.$month.'月有29天';
                $text = '29';
            }
            else{
                // $text = $year.'年的'.$month.'月有28天';
                $text = '28';
            }
        }
        else{

            // $text = $year.'年的'.$month.'月有30天';
            $text = '30';
        }
        return $y.'-'.$m.'-'.$text;
    }

    public function getSuccessOrder($orders, $times = null, $tag = false)
    {

        if (count($times) == 2 && !$tag) {
            $dates = $this -> getDates($times[0], $times[1]);
        } else if ($tag) {
            $dates = $times;
        } else {
            $dates = $this -> getDates();
        }
        $data = []; $z = 0; $orderDates = [];
        $orderTotalCount = 0;
        $orderTotalSuccessCount = 0;
        foreach ($dates as $k => $v) {
            $result = [];
            $result['orderCount'] = 0;
            $orderSuccessCount = 0;
            foreach ($orders as $key => $value) {
                $orderDate = date('Y-m', $orders[$key]['success_time']);
                $orderStatus = $orders[$key]['status'] >= 2 && $orders[$key]['status'] != 7;
                $orderStatus2 = $orders[$key]['status'] == -1;
                if ($dates[$k] == $orderDate && ($orderStatus || $orderStatus2)) {
                    $result['orderCount'] ++ ;
                    $orderTotalCount ++;
                }
                if ($dates[$k] == $orderDate && $orderStatus) {
                    $orderSuccessCount ++ ;
                    $orderTotalSuccessCount ++;
                }
            }

            //月订单统计
            $result['orderRatio'] = $orderSuccessCount.':'.$result['orderCount'];
            $orderSuccessl = $orderSuccessCount / $result['orderCount'] * 100;
            $orderSuccessl = $orderSuccessl ? $orderSuccessl : 0;
            $result['orderRate'] = $orderSuccessl;
            $data[$z] = $result;
            $z ++;
            //总订单统计
            $orderTotal['orderTotalCount'] = $orderTotalCount;
            $orderTotal['orderTotalRatio'] = $orderTotalSuccessCount.':'.$orderTotalCount;
            $orderTotal['orderTotalRate'] = $orderTotalSuccessCount / $orderTotalCount * 100;
            $orderTotal['orderTotalRate'] = $orderTotal['orderTotalRate'] ? $orderTotal['orderTotalRate'] : 0;
        }
        array_unshift($data,$orderTotal);
        return $data;
    }

    public function getOverdueOrder($order_month_pay, $orders = [], $times = null, $tag = false)
    {
        if (count($times) == 2 && !$tag) {
            $dates = $this -> getDates($times[0], $times[1]);
        } else if ($tag) {
            $dates = $times;
        } else {
            $dates = $this -> getDates();
        }
        $data = [];$z = 0;
        $orderTotalOverdueCount = 0;
        $orderTotalSuccessCount = 0;
        $results = [];
        foreach ($order_month_pay as $k => $v) {
            $orderDate = date('Y-m', $order_month_pay[$k]['pay_time']);
            if ($order_month_pay[$k]['overdue_status'] == 1) {
                $results[$orderDate]['orderCount'] ++;
            }
            $results[$orderDate]['orderSuccessCount'] ++;
        }
        foreach ($dates as $k => $v) {
            $result = [];
            if (!$results[$v]) {
                $results[$v]['orderCount'] = 0;
                $results[$v]['orderSuccessCount'] = 0;
            }
            $result['orderCount'] = $results[$v]['orderCount'];
            $result['orderRatio'] = $result['orderCount'].':'.$results[$v]['orderSuccessCount'];
            $result['orderRate'] = $result['orderCount'] / $results[$v]['orderSuccessCount'] * 100;
            $result['orderRate'] = $result['orderRate'] ? $result['orderRate'] : 0;
            $data[] = $result;
        }
        foreach ($dates as $key => $value) {
            $result = []; $result['orderCount'] = 0; $orderSuccessCount = 0;
            foreach ($order_month_pay as $k => $v) {
                $orderDate = date('Y-m', $order_month_pay[$k]['pay_time']);
                if ($dates[$key] == $orderDate && $order_month_pay[$k]['overdue_status'] == 1) {
                    $result['orderCount'] ++;
//                    $orderTotalOverdueCount ++;
                }
                if ($dates[$key] == $orderDate) {
                    $orderSuccessCount ++;
//                    $orderTotalSuccessCount ++;
                }
            }
            foreach ($orders as $j => $i) {
                $orderDate = date('Y-m', $orders[$j]['create_time']);
                if ($dates[$key] == $orderDate) {
                    $tag = true; $tag1 = true;
                    foreach ($order_month_pay as $k => $v) {
                        if ($orders[$j]['orderid'] == $order_month_pay[$k]['orderid'] &&
                            $order_month_pay[$k]['overdue_status'] == 1 && $tag) {
                            $orderTotalOverdueCount ++;
                            $tag = false;
                        }
                        if ($orders[$j]['orderid'] == $order_month_pay[$k]['orderid'] && $tag1) {
                            $orderTotalSuccessCount ++;
                            $tag1 = false;
                        }
                        if (!$tag && !$tag1) {
                            break;
                        }
                    }
                }

            }
            $result['orderRatio'] = $result['orderCount'].':'.$orderSuccessCount;
            $result['orderRate'] = $result['orderCount'] / $orderSuccessCount * 100;
            $result['orderRate'] = $result['orderRate'] ? $result['orderRate'] : 0;
            $data[$z] = $result;
            $z++;
            $orderOverdue['orderTotalCount'] = $orderTotalOverdueCount;
            $orderOverdue['orderTotalRatio'] = $orderTotalOverdueCount.':'.$orderTotalSuccessCount;
            $orderOverdue['orderTotalRate'] = $orderTotalOverdueCount / $orderTotalSuccessCount * 100;
            $orderOverdue['orderTotalRate'] = $orderOverdue['orderTotalRate'] ? $orderOverdue['orderTotalRate'] : 0;
        }
        array_unshift($data, $orderOverdue);
        return $data;
    }

    public function findOrderIdOrderInfo($orderId)
    {
        $order_db = M('order');
        $admin_db = M('admin');
        $user_db = M('user');
        $city_db = M('city');
        $way_db = M('wayuser');
        $cars_db = M('cars');
        $order_operation_db = M('order_operation');
        $order_month_pay_db = M('order_month_pay');
        //查询所有的订单
        $order = $order_db -> where(array('orderid' => $orderId)) -> find();
        //根据订单查询用户
        $user = $user_db -> where(array('id' => $order['uid'])) -> find();
        //根据订单记录表查询GW
        $order_operation = $order_operation_db -> where(array('orderid' => $orderId, 'status' =>0)) -> find();
        //根据订单查询分期,首付
        $order_month_pay = $order_month_pay_db -> where(array('orderid' => $orderId)) -> select();
        //查询逾期数
        $order_overdue_count = $order_month_pay_db -> where(array('orderid'=> $orderId, 'overdue_status' => 1)) ->count();
        //查询还款数
        $order_returnend_count = $order_month_pay_db -> where(array('orderid' => $orderId, 'status' => 1)) -> count();
        //查询GW信息
        $gw = $admin_db -> where(array('usernum' => $order_operation['usernum'])) -> find();
        //查询CS信息
        $cs = $admin_db -> field('usernum') -> where('id='.$gw['pid']) -> find();
        //查询SZ信息
        $sz = $admin_db -> field('usernum') -> where('provinceid='.$gw['provinceid']) -> find();
        //查询省
        $province = $city_db -> where('id='.$gw['provinceid']) -> find();
        //查询市
        $city = $city_db -> where('id='.$gw['cityid']) -> find();
        //查询渠道
        $way = $way_db -> where('waynum='.$user['waynum']) -> find();
        //查询总金额
        $car = $cars_db -> field('jdc_price') -> where('carnum='.$order['carnum']) -> find();
        $end_times = [];
        foreach ($order_month_pay as $k => $v) {
            $order_month_pay[$k]['pay_time'] = date('Y-m-d',$order_month_pay[$k]['pay_time']);
        }
        $data = [];
        $data['orderid'] = $orderId;
        $data['create_time'] = date('Y-m-d',$order['create_time']);
        $data['status'] = $order['status'];
        $data['overdue'] = $order_overdue_count;
        $data['username'] = $user['fullanme'];
        $data['tel'] = $user['tel'];
        $data['waynum'] = $user['waynum'];
        $data['waystatus'] = $way['status'];
        $data['gwname'] = $gw['name'];
        $data['gwusernum'] = $gw['usernum'];
        $data['city'] = $city['name'];
        $data['csusernum'] = $cs['usernum'];
        $data['province'] = $province['name'];
        $data['szusernum'] = $sz['usernum'];
        $data['jdc_price'] = $car['jdc_price'];
        $data['money'] = $order_month_pay[0]['money'];
        $data['returnend'] = $order_returnend_count;
        $data['notend'] = count($order_month_pay) - $order_returnend_count;
        $data['end_times'] = $order_month_pay;
        return [$data];
    }

    public function findGwOrdersInfo($usernum)
    {
        $order_db = M('order');
        $admin_db = M('admin');
        $user_db = M('user');
        $city_db = M('city');
        $way_db = M('wayuser');
        $cars_db = M('cars');
        $order_operation_db = M('order_operation');
        $order_month_pay_db = M('order_month_pay');

        $admin = $admin_db -> where(array('usernum' => $usernum)) -> find();
        $cs = $admin_db -> field('usernum') -> where(array('id' => $admin['pid'])) -> find();
        $sz = $admin_db -> field('usernum') -> where(array('provinceid', $admin['provinceid'])) -> find();
        $order = $order_db -> where('status=6') -> select();
        $order_operation = $order_operation_db -> where(array('usernum' => $usernum, 'status' => 0)) -> select();
        $order_month_pay = $order_month_pay_db -> select();
        $users = $user_db -> select();
        $way = $way_db -> select();
        $city = $city_db -> select();
        $cars = $cars_db -> select();

        $orders = [];$z = 0;
        foreach ($order as $key => $value) {
            foreach ($order_operation as $k => $v) {
                if ($order[$key]['orderid'] == $order_operation[$k]['orderid']) {
                    $orders[$z] = $order[$key];
                    $z++;
                    break;
                }
            }
        }

        $data = []; $i = 0;
        foreach ($orders as $key => $value) {
            $result = []; $order_month = []; $z = 0; $overdueCount = 0; $returnend = 0;
            foreach ($order_month_pay as $k => $v) {
                if ($orders[$key]['orderid'] == $order_month_pay[$k]['orderid']) {
                    $orders[$key]['pay_time'] = date('Y-m-d',$order_month_pay[$k]['pay_time']);
                    $order_month[$z] = $orders[$key];
                    $result['money'] = $order_month_pay[$k]['money'];
                    $z++;
                }
                if ($orders[$key]['orderid'] == $order_month_pay[$k]['orderid'] && $order_month_pay[$k]['overdue_status'] == 1) {
                  $overdueCount++;
                }
                if ($orders[$key]['orderid'] == $order_month_pay[$k]['orderid'] && $order_month_pay[$k]['status'] == 1) {
                    $returnend++;
                }
            }

            foreach ($users as $k => $v) {
                if ($users[$k]['id'] == $orders[$key]['uid']) {
                    $result['username'] = $users[$k]['fullanme'];
                    $result['tel'] = $users[$k]['tel'];
                    $result['waynum'] = $users[$k]['waynum'];
                }
            }

            foreach ($way as $k => $v) {
                if ($way[$k]['waynum'] == $result['waynum']) {
                    $result['waystatus'] = $way[$k]['status'];
                    break;
                }
            }

            foreach ($city as $k => $v) {
                if ($city[$k]['id'] == $admin['provinceid']) {
                    $result['province'] = $city[$k]['name'];
                }
                if ($city[$k]['id'] == $admin['cityid']) {
                    $result['city'] = $city[$k]['name'];
                }
            }
            foreach ($cars as $k => $v) {
                if ($cars[$k]['carnum'] == $orders[$key]['carnum']) {
                    $result['jdc_price'] = $cars[$k]['jdc_price'];
                    break;
                }
            }
            $result['gwname'] = $admin['name'];
            $result['gwusernum'] = $admin['usernum'];
            $result['csusernum'] = $cs['usernum'];
            $result['szusernum'] = $sz['usernum'];
            $result['orderid'] = $orders[$key]['orderid'];
            $result['create_time'] = date('Y-m-d',$orders[$key]['create_time']);
            $result['status'] = $orders[$key]['status'];
            $result['overdue'] = $overdueCount;
            $result['returnend'] = $returnend;
            $result['notend'] = count($order_month) - $returnend;
            $result['end_times'] = $order_month;
            $data[$i] = $result;
            $i++;
        }
        return $data;
    }
}
